import sys

import psutil

import json
import os
from datetime import datetime, timedelta
from PySide6.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
                               QGridLayout, QLabel, QPushButton, QScrollArea, QFrame, QSizePolicy,
                               QTableWidget, QTableWidgetItem, QHeaderView, QAbstractItemView,
                               QSystemTrayIcon, QMenu, QMessageBox)
from PySide6.QtCore import QTimer, QThread, Signal, Qt, QPropertyAnimation, QEasingCurve, QRect, QSize
from PySide6.QtGui import QFont, QPalette, QColor, QLinearGradient, QPainter, QBrush, QPixmap, QIcon
from monitor import WorkMonitor
from network_monitor import NetworkMonitor
from analysis_dialog import AnalysisDialog
from theme_manager import ThemeManager
from theme_dialog import ThemeDialog

# 应用程序中英文名称映射表
APP_NAME_MAPPING = {
    # 浏览器类
    'chrome.exe': 'Chrome 浏览器',
    'firefox.exe': 'Firefox 火狐浏览器',
    'msedge.exe': 'Edge 浏览器',
    'safari': 'Safari 浏览器',
    'opera.exe': 'Opera 浏览器',
    'brave.exe': 'Brave 浏览器',
    'vivaldi.exe': 'Vivaldi 浏览器',
    'iexplore.exe': 'Internet Explorer',

    # 办公软件
    'winword.exe': 'Microsoft Word',
    'excel.exe': 'Microsoft Excel',
    'powerpnt.exe': 'Microsoft PowerPoint',
    'outlook.exe': 'Microsoft Outlook',
    'onenote.exe': 'Microsoft OneNote',
    'teams.exe': 'Microsoft Teams',
    'msaccess.exe': 'Microsoft Access',
    'visio.exe': 'Microsoft Visio',
    'project.exe': 'Microsoft Project',
    'quarkclouddrive.exe': '夸克网盘',

    # WPS 办公套件
    'wps.exe': 'WPS 文字',
    'et.exe': 'WPS 表格',
    'wpp.exe': 'WPS 演示',
    'wpspdf.exe': 'WPS PDF',
    'wpscloud.exe': 'WPS 云文档',

    # 开发工具
    'code.exe': 'Visual Studio Code',
    'devenv.exe': 'Visual Studio',
    'pycharm64.exe': 'PyCharm',
    'pycharm.exe': 'PyCharm',
    'idea64.exe': 'IntelliJ IDEA',
    'webstorm64.exe': 'WebStorm',
    'sublime_text.exe': 'Sublime Text',
    'notepad++.exe': 'Notepad++',
    'atom.exe': 'Atom 编辑器',
    'eclipse.exe': 'Eclipse',
    'androidstudio64.exe': 'Android Studio',
    'xcode': 'Xcode',
    'git-bash.exe': 'Git Bash',
    'cmd.exe': '命令提示符',
    'powershell.exe': 'PowerShell',
    'terminal': '终端',
    'iterm2': 'iTerm2',

    # 设计软件
    'photoshop.exe': 'Adobe Photoshop',
    'illustrator.exe': 'Adobe Illustrator',
    'indesign.exe': 'Adobe InDesign',
    'premiere.exe': 'Adobe Premiere Pro',
    'afterfx.exe': 'Adobe After Effects',
    'lightroom.exe': 'Adobe Lightroom',
    'acrobat.exe': 'Adobe Acrobat',
    'figma.exe': 'Figma',
    'sketch': 'Sketch',
    'canva.exe': 'Canva',
    'blender.exe': 'Blender',
    'maya.exe': 'Autodesk Maya',
    '3dsmax.exe': '3ds Max',
    'autocad.exe': 'AutoCAD',

    # 音视频软件
    'vlc.exe': 'VLC 媒体播放器',
    'potplayer.exe': 'PotPlayer',
    'kmplayer.exe': 'KMPlayer',
    'foobar2000.exe': 'Foobar2000',
    'spotify.exe': 'Spotify',
    'itunes.exe': 'iTunes',
    'music': '音乐',
    'quicktime player': 'QuickTime Player',
    'audacity.exe': 'Audacity',
    'obs64.exe': 'OBS Studio',
    'bandicam.exe': 'Bandicam',
    'camtasia.exe': 'Camtasia',

    # 社交通讯
    'wechat.exe': '微信',
    'qq.exe': 'QQ',
    'tim.exe': 'TIM',
    'dingtalk.exe': '钉钉',
    'feishu.exe': '飞书',
    'telegram.exe': 'Telegram',
    'discord.exe': 'Discord',
    'slack.exe': 'Slack',
    'skype.exe': 'Skype',
    'zoom.exe': 'Zoom',
    'tencent meeting.exe': '腾讯会议',
    'whatsapp.exe': 'WhatsApp',

    # 游戏平台与启动器
    'steam.exe': 'Steam',
    'epicgameslauncher.exe': 'Epic Games 启动器',
    'origin.exe': 'Origin 平台',
    'uplay.exe': '育碧 Uplay',
    'battle.net.exe': '暴雪战网',
    'wegame.exe': 'WeGame',
    'goggalaxy.exe': 'GOG Galaxy',
    'riotclient.exe': 'Riot 客户端',
    'minecraftlauncher.exe': 'Minecraft 启动器',
    'robloxplayer.exe': 'Roblox 播放器',
    'leagueclientux.exe': '英雄联盟',
    'valorant.exe': '无畏契约',

    # 热门游戏本体（新增腾讯与 Steam 游戏）
    'crossfire.exe': '穿越火线',
    '2k23.exe': 'NBA 2K23',
    'cs2.exe': '反恐精英2',
    'pubg.exe': '绝地求生',
    'fortnite.exe': '堡垒之夜',
    'cyberpunk2077.exe': '赛博朋克2077',
    'eldenring.exe': '艾尔登法环',
    'genshinimpact.exe': '原神',
    'honkaiimpact3rd.exe': '崩坏3',
    'overwatch.exe': '守望先锋',
    'worldofwarcraft.exe': '魔兽世界',
    'starcraftii.exe': '星际争霸2',
    'diabloiv.exe': '暗黑破坏神4',
    'fallout76.exe': '辐射76',
    'reddeadredemption2.exe': '荒野大镖客2',
    'thewitcher3.exe': '巫师3',
    'apex.exe': 'Apex 英雄',
    'rocketleague.exe': '火箭联盟',
    'callofduty.exe': '使命召唤',
    'rainbowsixsiege.exe': '彩虹六号：围攻',
    'finalfantasyxiv.exe': '最终幻想14',
    'marvelsspiderman.exe': '漫威蜘蛛侠',
    'minecraft.exe': 'Minecraft',
    'terraria.exe': '泰拉瑞亚',
    'stardewvalley.exe': '星露谷物语',
    'amongus.exe': 'Among Us',
    'phasmophobia.exe': '恐鬼症',
    'grounded.exe': '禁闭求生',
    'subnautica.exe': '深海迷航',
    'destiny2.exe': '命运2',
    'haloinfinite.exe': '光环：无限',
    'metroidprimeremastered.exe': '银河战士Prime 重制版',
    'pokemonscarlet.exe': '宝可梦朱',
    'pokemonviolet.exe': '宝可梦紫',
    'legendofzelda.exe': '塞尔达传说：王国之泪',
    'supermarioodyssey.exe': '超级马力欧奥德赛',
    'mariokart8deluxe.exe': '马力欧卡丁车8豪华版',
    'animalcrossing.exe': '动物森友会',
    'splatoon3.exe': '斯普拉遁3',
    'xenobladechronicles3.exe': '异度神剑3',
    'fireemblemengage.exe': '火焰之纹章：结合',
    'monsterhunterrise.exe': '怪物猎人崛起',
    'zeldaocarinaoftime.exe': '塞尔达传说：时之笛',
    'mario3dworld.exe': '超级马力欧3D世界',
    'streetfighter6.exe': '街头霸王6',
    'tekken8.exe': '铁拳8',
    'mortalkombat11.exe': '真人快打11',
    'guiltygearstrive.exe': '罪恶装备：奋战',
    'soulcalibur6.exe': '刀魂6',
    'kingoffightersxv.exe': '拳皇15',
    'fifa23.exe': 'FIFA 23',
    'footballmanager2023.exe': '足球经理2023',
    'nhl23.exe': 'NHL 23',
    'mlbtheshow23.exe': 'MLB The Show 23',
    'f123.exe': 'F1 23',
    'madden23.exe': '麦登橄榄球23',
    'gta5.exe': '侠盗猎车手5',
    'reddeadredemption.exe': '荒野大镖客：救赎',
    'sanandreas.exe': '侠盗猎车手：圣安地列斯',
    'vicecity.exe': '侠盗猎车手：罪恶都市',
    'minecraftbedrock.exe': 'Minecraft 基岩版',
    'robloxstudio.exe': 'Roblox 工作室',

    # 系统工具
    'explorer.exe': '文件资源管理器',
    'taskmgr.exe': '任务管理器',
    'regedit.exe': '注册表编辑器',
    'msconfig.exe': '系统配置',
    'control.exe': '控制面板',
    'calc.exe': '计算器',
    'notepad.exe': '记事本',
    'mspaint.exe': '画图',
    'snipping tool.exe': '截图工具',
    'finder': '访达',
    'activity monitor': '活动监视器',
    'system preferences': '系统偏好设置',

    # 下载工具
    'thunder.exe': '迅雷',
    'bittorrent.exe': 'BitTorrent',
    'utorrent.exe': 'uTorrent',
    'fdm.exe': 'Free Download Manager',
    'idm.exe': 'Internet Download Manager',
    'aria2c.exe': 'Aria2',

    # 压缩工具
    'winrar.exe': 'WinRAR',
    '7zfm.exe': '7-Zip',
    'bandizip.exe': 'BandiZip',
    'peazip.exe': 'PeaZip',

    # 安全软件
    '360se.exe': '360安全浏览器',
    '360safe.exe': '360安全卫士',
    'qqpcmgr.exe': '腾讯电脑管家',
    'qqpctray.exe': '腾讯电脑管家',
    'kxescore.exe': '金山毒霸',
    'avast.exe': 'Avast',
    'avg.exe': 'AVG',
    'kaspersky.exe': '卡巴斯基',
    'mcafee.exe': '迈克菲',

    # 输入法
    'sogouinput.exe': '搜狗输入法',
    'qqpinyin.exe': 'QQ拼音输入法',
    'baiduinput.exe': '百度输入法',
    'microsoftpinyin.exe': '微软拼音输入法',

    # 云存储
    'baidunetdisk.exe': '百度网盘',
    'alidrivedesktop.exe': '阿里云盘',
    'onedrive.exe': 'OneDrive',
    'dropbox.exe': 'Dropbox',
    'googledrive.exe': 'Google Drive',
    'icloud.exe': 'iCloud',
    '115pc.exe': '115网盘',

    # 阅读软件
    'adobereader.exe': 'Adobe Reader',
    'foxit reader.exe': '福昕PDF阅读器',
    'sumatra pdf.exe': 'Sumatra PDF',
    'kindle.exe': 'Kindle',
    'calibre.exe': 'Calibre',

    # 虚拟机
    'vmware.exe': 'VMware',
    'virtualbox.exe': 'VirtualBox',
    'parallels desktop.exe': 'Parallels Desktop',
    'hyper-v.exe': 'Hyper-V',

    # 数据库工具
    'navicat.exe': 'Navicat',
    'dbeaver.exe': 'DBeaver',
    'mysql workbench.exe': 'MySQL Workbench',
    'pgadmin.exe': 'pgAdmin',
    'redis-desktop-manager.exe': 'Redis Desktop Manager',

    # 网络工具
    'wireshark.exe': 'Wireshark',
    'putty.exe': 'PuTTY',
    'winscp.exe': 'WinSCP',
    'filezilla.exe': 'FileZilla',
    'postman.exe': 'Postman',
    'charles.exe': 'Charles',

    # 其他常用软件
    'everything.exe': 'Everything 搜索',
    'bandicam.exe': 'Bandicam 录屏',
    'snipaste.exe': 'Snipaste 截图',
    'typora.exe': 'Typora',
    'obsidian.exe': 'Obsidian',
    'notion.exe': 'Notion',
    'evernote.exe': '印象笔记',
    'youdao dict.exe': '有道词典',
    'translate.exe': '翻译软件',
    'f.lux.exe': 'f.lux',
    'ccleaner.exe': 'CCleaner',
    'driverbooster.exe': 'Driver Booster',
}

def get_resource_path(relative_path):
    """获取资源的绝对路径，支持开发环境和打包后的环境"""
    if getattr(sys, 'frozen', False):  # 打包后环境
        base_path = sys._MEIPASS  # nuitka 使用 _MEIPASS 存储临时文件
    else:  # 开发环境
        base_path = os.path.dirname(os.path.abspath(__file__))
    return os.path.join(base_path, relative_path)


def get_chinese_app_name(original_name):
    """
    将英文应用名称转换为中文名称

    Args:
        original_name (str): 原始应用名称

    Returns:
        str: 中文应用名称，如果没有找到映射则返回原名称
    """
    if not original_name:
        return "未知应用"

    # 转换为小写进行匹配
    name_lower = original_name.lower()

    # 直接匹配
    if name_lower in APP_NAME_MAPPING:
        return APP_NAME_MAPPING[name_lower]


    # 模糊匹配 - 去除常见后缀
    name_without_ext = name_lower.replace('.exe', '').replace('.app', '')
    if name_without_ext in APP_NAME_MAPPING:
        return APP_NAME_MAPPING[name_without_ext]

    # 部分匹配 - 检查是否包含关键词
    for key, value in APP_NAME_MAPPING.items():
        key_base = key.replace('.exe', '').replace('.app', '')
        if key_base in name_lower or name_without_ext in key_base:
            return value

    # 特殊处理一些常见模式
    if 'chrome' in name_lower:
        return 'Chrome 浏览器'
    elif 'firefox' in name_lower:
        return 'Firefox 浏览器'
    elif 'wechat' in name_lower or '微信' in original_name:
        return '微信'
    elif 'qq' in name_lower and 'qqpc' not in name_lower:
        return 'QQ'
    elif 'office' in name_lower:
        return 'Microsoft Office'
    elif 'steam' in name_lower:
        return 'Steam'
    elif 'python' in name_lower:
        return 'Python'
    elif 'java' in name_lower:
        return 'Java'
    elif 'node' in name_lower:
        return 'Node.js'
    elif 'code' in name_lower and 'vs' in name_lower:
        return 'Visual Studio Code'
    elif 'idea' in name_lower:
        return 'IntelliJ IDEA'
    elif 'pycharm' in name_lower:
        return 'PyCharm'
    elif 'photoshop' in name_lower or 'ps' in name_lower:
        return 'Adobe Photoshop'
    elif 'word' in name_lower:
        return 'Microsoft Word'
    elif 'excel' in name_lower:
        return 'Microsoft Excel'
    elif 'powerpoint' in name_lower or 'ppt' in name_lower:
        return 'Microsoft PowerPoint'
    elif 'outlook' in name_lower:
        return 'Microsoft Outlook'
    elif 'teams' in name_lower:
        return 'Microsoft Teams'
    elif 'zoom' in name_lower:
        return 'Zoom'
    elif 'discord' in name_lower:
        return 'Discord'
    elif 'telegram' in name_lower:
        return 'Telegram'
    elif 'spotify' in name_lower:
        return 'Spotify'
    elif 'vlc' in name_lower:
        return 'VLC 媒体播放器'
    elif 'notepad' in name_lower:
        if '++' in name_lower:
            return 'Notepad++'
        else:
            return '记事本'
    elif 'calculator' in name_lower or 'calc' in name_lower:
        return '计算器'
    elif 'explorer' in name_lower:
        return '文件资源管理器'
    elif 'terminal' in name_lower:
        return '终端'
    elif 'cmd' in name_lower:
        return '命令提示符'
    elif 'powershell' in name_lower:
        return 'PowerShell'
    elif name_lower == "browser.exe":
        try:
            # 遍历所有进程，找到名称为 browser.exe 且路径含 WeGame 的进程
            for proc in psutil.process_iter(['name', 'exe']):
                proc_name = proc.info.get('name', '').lower()
                proc_exe = proc.info.get('exe', '') or ''  # 进程的可执行文件路径

                # 匹配条件：进程名是 browser.exe，且路径包含 "wegame"（不区分大小写）
                if proc_name == "browser.exe" and 'wegame' in proc_exe.lower():
                    return "WeGame 内嵌浏览器"
        except (psutil.AccessDenied, psutil.NoSuchProcess):
            # 忽略无权限或已结束的进程
            pass

    # 如果都没有匹配到，返回原名称（首字母大写）
    return original_name.title() if original_name else "未知应用"


class AnimatedLabel(QLabel):
    def __init__(self, text="", parent=None):
        super().__init__(text, parent)
        self._animation_running = False

    def animate_update(self, new_text):
        if self._animation_running:
            return

        old_text = self.text()
        if old_text == new_text:
            return

        self._animation_running = True
        self.setText(new_text)

        # 简单的缩放效果，避免频繁动画
        QTimer.singleShot(100, lambda: setattr(self, '_animation_running', False))


class MetricCard(QFrame):
    def __init__(self, title, icon, parent=None):
        super().__init__(parent)
        self.title = title
        self.icon = icon
        self.setup_ui(title, icon)
        self.setup_adaptive_features()

    def setup_adaptive_features(self):
        """设置自适应功能"""
        # 获取屏幕分辨率
        screen = QApplication.primaryScreen()
        screen_size = screen.size()
        screen_width = screen_size.width()
        screen_height = screen_size.height()

        # 根据屏幕分辨率调整卡片大小
        self.setMinimumHeight(int(screen_height * 0.2))
        self.setMinimumWidth(int(screen_width * 0.15))

        # 设置字体大小自适应
        font = self.title_label.font()
        font.setPixelSize(int(screen_height * 0.02))
        self.title_label.setFont(font)

        font = self.value_label.font()
        font.setPixelSize(int(screen_height * 0.04))
        self.value_label.setFont(font)

    def setup_ui(self, title, icon):
        self.setFrameStyle(QFrame.Shape.NoFrame)
        self.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True)
        self.setMinimumHeight(220)
        self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)

        layout = QVBoxLayout(self)
        layout.setSpacing(18)
        layout.setContentsMargins(24, 24, 24, 24)

        # 标题
        self.title_label = QLabel(f"{icon} {title}")
        self.title_label.setFont(QFont("SF Pro Display", 16, QFont.Weight.Bold))
        self.title_label.setMinimumHeight(28)
        layout.addWidget(self.title_label)

        # 主要数值
        self.value_label = AnimatedLabel("0")
        self.value_label.setFont(QFont("SF Pro Display", 42, QFont.Weight.Bold))
        self.value_label.setMinimumHeight(58)
        layout.addWidget(self.value_label)

        # 单位
        self.unit_label = QLabel("")
        self.unit_label.setFont(QFont("SF Pro Display", 14))
        self.unit_label.setMinimumHeight(24)
        layout.addWidget(self.unit_label)

        # 进度条容器
        progress_container = QWidget()
        progress_container.setFixedHeight(16)
        progress_layout = QHBoxLayout(progress_container)
        progress_layout.setContentsMargins(0, 4, 0, 4)

        self.progress_bg = QFrame()
        self.progress_bg.setFixedHeight(8)

        self.progress_fill = QFrame(self.progress_bg)
        self.progress_fill.setFixedHeight(6)
        self.progress_fill.setFixedWidth(0)
        self.progress_fill.move(1, 1)

        progress_layout.addWidget(self.progress_bg)
        layout.addWidget(progress_container)

        # 统计网格
        self.stats_widget = QWidget()
        self.stats_layout = QGridLayout(self.stats_widget)
        self.stats_layout.setSpacing(12)
        self.stats_layout.setContentsMargins(0, 15, 0, 0)
        layout.addWidget(self.stats_widget)

        layout.addStretch()

        # 缓存上次的值，避免频繁更新
        self._last_value = None
        self._last_progress = None

    def apply_theme(self, theme_data):
        """应用主题到卡片"""
        self.setStyleSheet(f"""
            MetricCard {{
                background: {theme_data['card_bg']};
                border: 2px solid {theme_data['border']};
                border-radius: 24px;
                margin: 8px;
                backdrop-filter: blur(10px);
                box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1), 
                           0 4px 16px rgba(0, 0, 0, 0.05),
                           inset 0 1px 0 rgba(255, 255, 255, 0.8);
            }}
            QLabel {{
                color: {theme_data['text']};
                background: transparent;
                border: none;
                line-height: 1.4;
            }}
        """)

        # 更新标题样式
        self.title_label.setStyleSheet(f"""
            color: {theme_data['text']};
            font-weight: 700;
            text-shadow: 0 1px 2px rgba(255, 255, 255, 0.8);
            padding: 4px 0px;
            line-height: 24px;
        """)

        # 更新数值样式
        self.value_label.setStyleSheet(f"""
            color: {theme_data['text']};
            font-weight: 800;
            text-shadow: 0 2px 4px rgba(255, 255, 255, 0.9);
            padding: 8px 0px;
            line-height: 50px;
        """)

        # 更新单位样式
        self.unit_label.setStyleSheet(f"""
            color: {theme_data['text_secondary']};
            font-weight: 600;
            text-shadow: 0 1px 2px rgba(255, 255, 255, 0.7);
            padding: 2px 0px;
            line-height: 20px;
        """)

        # 更新进度条样式
        self.progress_bg.setStyleSheet(f"""
            QFrame {{
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 rgba(203, 213, 225, 0.6), 
                    stop:1 rgba(226, 232, 240, 0.8));
            border-radius: 4px;
            border: 1px solid {theme_data['border']};
                box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1);
            }}
        """)

        self.progress_fill.setStyleSheet(f"""
            QFrame {{
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 {theme_data['gradient_start']}, 
                    stop:0.5 {theme_data['primary']}, 
                    stop:1 {theme_data['gradient_end']});
                border-radius: 3px;
                border: none;
                box-shadow: 0 1px 3px {theme_data['primary']}40;
            }}
        """)

        # 保存主题数据供统计项使用
        self._theme_data = theme_data

    def update_value(self, value, unit="", progress=0):
        # 只在值真正改变时更新
        if self._last_value != value:
            self.value_label.animate_update(str(value))
            self._last_value = value

        self.unit_label.setText(unit)

        # 只在进度真正改变时更新
        if abs((self._last_progress or 0) - progress) > 0.01:
            bg_width = self.progress_bg.width() - 2
            new_width = max(0, int(bg_width * min(progress, 1.0)))
            self.progress_fill.setFixedWidth(new_width)
            self._last_progress = progress

    def add_stat(self, row, col, value, label):
        # 清除指定位置的旧组件
        item = self.stats_layout.itemAtPosition(row, col)
        if item:
            widget = item.widget()
            if widget:
                widget.setParent(None)

        stat_frame = QFrame()
        stat_frame.setMinimumHeight(80)

        # 获取当前主题数据
        theme_data = getattr(self, '_theme_data', {
            'primary': '#3b82f6',
            'secondary': '#0e7490',
            'text': '#1e293b'
        })

        stat_frame.setStyleSheet(f"""
            QFrame {{
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 rgba(59, 130, 246, 0.12), 
                    stop:1 rgba(37, 99, 235, 0.08));
                border: none;
                padding: 16px;
                backdrop-filter: blur(5px);
                box-shadow: 0 2px 8px rgba(59, 130, 246, 0.15),
                           inset 0 1px 0 rgba(255, 255, 255, 0.6);
            }}
            QFrame:hover {{
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 rgba(59, 130, 246, 0.18), 
                    stop:1 rgba(37, 99, 235, 0.12));
                border: 1px solid {theme_data['secondary']};
            }}
            QLabel {{
                line-height: 1.3;
                color: {theme_data['text']};
            }}
        """)

        stat_layout = QVBoxLayout(stat_frame)
        stat_layout.setAlignment(Qt.AlignmentFlag.AlignCenter)
        stat_layout.setSpacing(8)
        stat_layout.setContentsMargins(8, 8, 8, 8)

        value_label = QLabel(str(value))
        value_label.setFont(QFont("SF Pro Display", 20, QFont.Weight.Bold))
        value_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        value_label.setStyleSheet(f"""
            color: {theme_data['primary']};
            font-weight: 800;
            text-shadow: 0 1px 2px rgba(255, 255, 255, 0.8);
            padding: 2px 0px;
            line-height: 26px;
        """)
        value_label.setMinimumHeight(30)

        label_label = QLabel(label)
        label_label.setFont(QFont("SF Pro Display", 10))
        label_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        label_label.setStyleSheet(f"""
            color: {theme_data['text']};
            font-weight: 600;
            text-shadow: 0 1px 1px rgba(255, 255, 255, 0.7);
            padding: 2px 0px;
            line-height: 14px;
        """)
        label_label.setWordWrap(True)
        label_label.setMinimumHeight(18)

        stat_layout.addWidget(value_label)
        stat_layout.addWidget(label_label)

        self.stats_layout.addWidget(stat_frame, row, col)


class AppTableWidget(QFrame):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True)
        self.setMinimumWidth(500)  # 增加最小宽度以容纳更多列
        self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)

        layout = QVBoxLayout(self)
        layout.setContentsMargins(24, 24, 24, 24)
        layout.setSpacing(18)

        # 标题
        self.title_label = QLabel("📱 应用使用详情")
        self.title_label.setFont(QFont("SF Pro Display", 16, QFont.Weight.Bold))
        self.title_label.setMinimumHeight(28)
        layout.addWidget(self.title_label)

        # 创建表格
        self.table = QTableWidget()
        self.table.setDisabled(True)
        self.table.setColumnCount(6)  # 增加到6列
        self.table.setHorizontalHeaderLabels(["排名", "应用名称", "使用时长", "开始时间", "结束时间", "状态"])

        # 设置表格属性
        self.table.setAlternatingRowColors(True)
        self.table.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows)
        self.table.setSelectionMode(QAbstractItemView.SelectionMode.SingleSelection)
        self.table.setVerticalScrollMode(QAbstractItemView.ScrollMode.ScrollPerPixel)
        self.table.setHorizontalScrollMode(QAbstractItemView.ScrollMode.ScrollPerPixel)
        self.table.setSortingEnabled(False)  # 禁用排序，我们自己控制

        # 设置表头
        header = self.table.horizontalHeader()
        header.setSectionResizeMode(0, QHeaderView.ResizeMode.Fixed)  # 排名列固定宽度
        header.setSectionResizeMode(1, QHeaderView.ResizeMode.Stretch)  # 应用名称列拉伸
        header.setSectionResizeMode(2, QHeaderView.ResizeMode.Fixed)  # 使用时长列固定宽度
        header.setSectionResizeMode(3, QHeaderView.ResizeMode.Fixed)  # 开始时间列固定宽度
        header.setSectionResizeMode(4, QHeaderView.ResizeMode.Fixed)  # 结束时间列固定宽度
        header.setSectionResizeMode(5, QHeaderView.ResizeMode.Fixed)  # 状态列固定宽度

        # 设置列宽
        self.table.setColumnWidth(0, 80)  # 排名
        self.table.setColumnWidth(2, 100)  # 使用时长
        self.table.setColumnWidth(3, 100)  # 开始时间
        self.table.setColumnWidth(4, 100)  # 结束时间
        self.table.setColumnWidth(5, 100)  # 状态

        # 隐藏垂直表头
        self.table.verticalHeader().setVisible(False)

        # 设置行高
        self.table.verticalHeader().setDefaultSectionSize(42)

        layout.addWidget(self.table)

        # 缓存应用数据，避免频繁重建
        self._last_apps_data = None

    def apply_theme(self, theme_data):
        """应用主题到表格"""
        self.setStyleSheet(f"""
            AppTableWidget {{
                background: {theme_data['card_bg']};
                border: 2px solid rgba(148, 163, 184, 0.3);
                border-radius: 24px;
                margin: 8px;
                backdrop-filter: blur(10px);
                box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1), 
                           0 4px 16px rgba(0, 0, 0, 0.05),
                           inset 0 1px 0 rgba(255, 255, 255, 0.8);
            }}
            QLabel {{
                color: {theme_data['text']};
                background: transparent;
                border: none;
                line-height: 1.4;
            }}
        """)

        # 更新标题样式
        self.title_label.setStyleSheet(f"""
            color: {theme_data['text']};
            font-weight: 700;
            text-shadow: 0 1px 2px rgba(255, 255, 255, 0.8);
            padding: 4px 0px;
            line-height: 24px;
        """)

        # 设置表格样式
        self.table.setStyleSheet(f"""
            QTableWidget {{
                background: transparent;
                border: none;
                border-radius: 12px;
                gridline-color: rgba(203, 213, 225, 0.4);
                selection-background-color: rgba(59, 130, 246, 0.15);
                alternate-background-color: rgba(248, 250, 252, 0.5);
            }}

            QTableWidget::item {{
                padding: 10px 6px;
                border: none;
                border-bottom: 1px solid rgba(226, 232, 240, 0.6);
                color: {theme_data['text']};
                font-weight: 500;
                text-shadow: 0 1px 1px rgba(255, 255, 255, 0.8);
                font-size: 11px;
            }}

            QTableWidget::item:selected {{
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 rgba(59, 130, 246, 0.15), 
                    stop:1 rgba(37, 99, 235, 0.1));
                color: {theme_data['primary']};
                font-weight: 600;
            }}

            QTableWidget::item:hover {{
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 rgba(59, 130, 246, 0.08), 
                    stop:1 rgba(37, 99, 235, 0.05));
            }}

            QHeaderView::section {{
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 {theme_data['primary']}, 
                    stop:1 {theme_data['secondary']});
                border: none;
                border-bottom: 2px solid {theme_data['primary']};
                border-right: 1px solid rgba(203, 213, 225, 0.4);
                padding: 10px 6px;
                color: white;
                font-weight: 700;
                font-size: 11px;
                text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
                text-align: center;
            }}

            QHeaderView::section:first {{
                border-top-left-radius: 12px;
            }}

            QHeaderView::section:last {{
                border-top-right-radius: 12px;
                border-right: none;
            }}

            QScrollBar:vertical {{
                background: rgba(241, 245, 249, 0.8);
                width: 10px;
                border-radius: 5px;
                margin: 0;
                border: 1px solid rgba(203, 213, 225, 0.5);
            }}

            QScrollBar::handle:vertical {{
                background: {theme_data['primary']};
                border-radius: 4px;
                min-height: 20px;
                border: none;
                box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
            }}

            QScrollBar::handle:vertical:hover {{
                background: {theme_data['secondary']};
            }}

            QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {{
                height: 0px;
                border: none;
            }}

            QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {{
                background: transparent;
            }}
        """)

    def update_apps(self, apps_data):
        # 检查数据是否真的改变了
        apps_summary = [(app['name'], int(app['total_time']),
                         app.get('current_session_start'), app.get('last_end_time'))
                        for app in apps_data[:20]]
        if self._last_apps_data == apps_summary:
            return

        self._last_apps_data = apps_summary

        # 按使用时长递减排序
        sorted_apps = sorted(apps_data, key=lambda x: x['total_time'], reverse=True)[:20]

        # 设置表格行数
        self.table.setRowCount(len(sorted_apps))

        # 填充数据
        for i, app in enumerate(sorted_apps):
            # 排名
            rank_item = QTableWidgetItem(str(i + 1))
            rank_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
            rank_item.setFont(QFont("SF Pro Display", 10, QFont.Weight.Bold))

            # 根据排名设置不同颜色
            if i == 0:  # 第一名
                rank_item.setForeground(QColor("#dc2626"))  # 红色
            elif i == 1:  # 第二名
                rank_item.setForeground(QColor("#ea580c"))  # 橙色
            elif i == 2:  # 第三名
                rank_item.setForeground(QColor("#ca8a04"))  # 黄色
            else:
                rank_item.setForeground(QColor("#64748b"))  # 灰色

            self.table.setItem(i, 0, rank_item)

            # 应用名称
            name_item = QTableWidgetItem(get_chinese_app_name(app['name']))
            name_item.setFont(QFont("SF Pro Display", 10, QFont.Weight.Bold))
            name_item.setForeground(QColor("#1e293b"))
            self.table.setItem(i, 1, name_item)

            # 使用时长
            time_str = self.format_time(app['total_time'])
            time_item = QTableWidgetItem(time_str)
            time_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
            time_item.setFont(QFont("SF Pro Display", 9, QFont.Weight.Medium))
            time_item.setForeground(QColor("#475569"))
            self.table.setItem(i, 2, time_item)

            # 开始时间
            start_time = app.get('current_session_start') or app.get('last_start_time')
            if start_time:
                start_time_str = datetime.fromtimestamp(start_time).strftime("%H:%M:%S")
            else:
                start_time_str = "--:--:--"

            start_item = QTableWidgetItem(start_time_str)
            start_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
            start_item.setFont(QFont("SF Pro Display", 9, QFont.Weight.Medium))
            start_item.setForeground(QColor("#059669"))  # 绿色
            self.table.setItem(i, 3, start_item)

            # 结束时间
            end_time = app.get('last_end_time')
            if end_time:
                end_time_str = datetime.fromtimestamp(end_time).strftime("%H:%M:%S")
                end_color = QColor("#dc2626")  # 红色表示已结束
            else:
                end_time_str = "使用中"
                end_color = QColor("#059669")  # 绿色表示正在使用

            end_item = QTableWidgetItem(end_time_str)
            end_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
            end_item.setFont(QFont("SF Pro Display", 9, QFont.Weight.Medium))
            end_item.setForeground(end_color)
            self.table.setItem(i, 4, end_item)

            # 状态
            if app.get('current_session_start') and not app.get('last_end_time'):
                status_text = "🟢 活跃"
                status_color = QColor("#059669")  # 绿色
            else:
                status_text = "⚪ 空闲"
                status_color = QColor("#64748b")  # 灰色

            status_item = QTableWidgetItem(status_text)
            status_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
            status_item.setFont(QFont("SF Pro Display", 9, QFont.Weight.Bold))
            status_item.setForeground(status_color)
            self.table.setItem(i, 5, status_item)

        # 如果没有数据，显示提示
        if not sorted_apps:
            self.table.setRowCount(1)
            no_data_item = QTableWidgetItem("暂无数据")
            no_data_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
            no_data_item.setFont(QFont("SF Pro Display", 12))
            no_data_item.setForeground(QColor("#94a3b8"))
            self.table.setItem(0, 1, no_data_item)

            # 合并单元格显示"暂无数据"
            self.table.setSpan(0, 0, 1, 6)

    def format_time(self, seconds):
        hours = int(seconds // 3600)
        minutes = int((seconds % 3600) // 60)
        secs = int(seconds % 60)
        if hours > 0:
            return f"{hours:02d}:{minutes:02d}:{secs:02d}"
        else:
            return f"{minutes:02d}:{secs:02d}"


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.is_background_running = True
        # 初始化统计
        self.peak_keys_per_min = 0
        # 缓存数据，避免频繁更新
        self._last_update_data = None
        # 初始化分析对话框
        self.analysis_dialog = None

        # 初始化主题管理器
        self.theme_manager = ThemeManager()

        self.setup_ui()
        self.setup_adaptive_features()
        self.setup_system_tray()

        # 应用当前主题
        self.apply_theme()

    def setup_adaptive_features(self):
        """设置自适应功能"""
        # 获取屏幕分辨率
        screen = QApplication.primaryScreen()
        screen_size = screen.size()
        screen_width = screen_size.width()
        screen_height = screen_size.height()

        # 根据屏幕分辨率调整窗口大小
        self.resize(int(screen_width * 0.8), int(screen_height * 0.8))

        # 设置窗口最小尺寸
        self.setMinimumSize(int(screen_width * 0.5), int(screen_height * 0.5))

        # 设置窗口居中显示
        self.move(int((screen_width - self.width()) / 2),
                  int((screen_height - self.height()) / 2))

    def setup_ui(self):
        self.setWindowTitle("牛马监控大屏")
        self.setGeometry(100, 100, 1800, 1000)  # 增加窗口尺寸
        self.setMinimumSize(960, 800)

        # 设置窗口属性，减少闪烁
        self.setAttribute(Qt.WidgetAttribute.WA_OpaquePaintEvent, True)
        self.setAttribute(Qt.WidgetAttribute.WA_NoSystemBackground, False)

        # 设置背景图片
        self.background_pixmap = QPixmap(get_resource_path("assets/background.png"))

        # 创建中央部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)

        # 主布局 - 调整为4列网格布局
        main_layout = QGridLayout(central_widget)
        main_layout.setSpacing(16)
        main_layout.setContentsMargins(20, 0, 20, 0)

        # 头部 - 跨所有列
        self.create_header()
        main_layout.addWidget(self.header_frame, 0, 0, 1, 4)  # 跨4列

        # 创建指标卡片
        self.keyboard_card = MetricCard("键盘输入", "⌨️")
        self.mouse_card = MetricCard("鼠标移动", "🖱️")
        self.time_card = MetricCard("工作时长", "⏱️")

        # 应用表格
        self.app_table = AppTableWidget()

        # 调整布局 - 左右各占一半
        main_layout.addWidget(self.keyboard_card, 1, 0, 1, 1)  # 第1列
        main_layout.addWidget(self.mouse_card, 1, 1, 1, 1)  # 第2列
        main_layout.addWidget(self.time_card, 2, 0, 1, 2)  # 跨第1-2列
        main_layout.addWidget(self.app_table, 1, 2, 2, 2)  # 跨第3-4列，占右半部分

        # 设置列的拉伸比例 - 左右各占一半
        main_layout.setColumnStretch(0, 1)  # 第1列
        main_layout.setColumnStretch(1, 1)  # 第2列
        main_layout.setColumnStretch(2, 1)  # 第3列 - 应用表格左半部分
        main_layout.setColumnStretch(3, 1)  # 第4列 - 应用表格右半部分

        # 设置行的拉伸比例
        main_layout.setRowStretch(0, 0)  # 头部固定高度
        main_layout.setRowStretch(1, 1)  # 第一行卡片
        main_layout.setRowStretch(2, 1)  # 第二行卡片

        # 初始化监控
        self.monitor = WorkMonitor()
        self.network_monitor = NetworkMonitor()
        self.monitor.start()
        # self.network_monitor.start()

        # 设置定时器更新界面
        self.update_timer = QTimer()
        self.update_timer.timeout.connect(self.update_display)
        self.update_timer.start(2000)  # 每2秒更新一次

        # 初始化统计
        self.peak_keys_per_min = 0

        # 缓存数据，避免频繁更新
        self._last_update_data = None

        # 初始化分析对话框
        self.analysis_dialog = None

        # 设置运行状态
        self.is_background_running = True

    def apply_theme(self):
        """应用当前主题"""
        theme_data = self.theme_manager.get_theme_data()

        # 应用主题到应用程序
        self.theme_manager.apply_theme_to_app(QApplication.instance())

        # 设置主窗口样式
        self.setStyleSheet(f"""
            QMainWindow {{
                background: {theme_data['background']};
            }}
            QPushButton {{
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 {theme_data['gradient_start']}, 
                    stop:1 {theme_data['gradient_end']});
                color: white;
                border-radius: 8px;
                padding: 10px 20px;
                font-weight: bold;
                border: none;
                min-width: 90px;
                min-height: 36px;
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            }}
            QPushButton:hover {{
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 {theme_data['accent']}, 
                    stop:1 {theme_data['primary']});
                box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);
                transform: translateY(-1px);
            }}
            QPushButton:pressed {{
                background: {theme_data['secondary']};
                box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
                transform: translateY(0px);
            }}
        """)

        # 应用主题到各个组件
        if hasattr(self, 'keyboard_card'):
            self.keyboard_card.apply_theme(theme_data)
            self.keyboard_card._theme_data = theme_data

        if hasattr(self, 'mouse_card'):
            self.mouse_card.apply_theme(theme_data)
            self.mouse_card._theme_data = theme_data

        if hasattr(self, 'time_card'):
            self.time_card.apply_theme(theme_data)
            self.time_card._theme_data = theme_data

        if hasattr(self, 'app_table'):
            self.app_table.apply_theme(theme_data)

        if hasattr(self, 'header_frame'):
            self.apply_header_theme(theme_data)

        # 更新时间标签样式
        if hasattr(self, 'time_label'):
            self.time_label.setStyleSheet(f"""
                color: {theme_data['text']};
                background: transparent;
                font-weight: 600;
            """)

    def apply_header_theme(self, theme_data):
        """应用主题到头部"""
        self.header_frame.setStyleSheet(f"""
            QFrame {{
                background: {theme_data['card_bg']};
                border: 2px solid {theme_data['border']};
                border-radius: 20px;
                margin: 8px;
                backdrop-filter: blur(15px);
                box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1), 
                           0 4px 16px rgba(0, 0, 0, 0.05),
                           inset 0 1px 0 rgba(255, 255, 255, 0.8);
            }}
            QLabel {{
                color: {theme_data['text']};
                background: transparent;
                border: none;
                line-height: 1.4;
            }}
        """)

    def on_theme_changed(self, theme_key):
        """主题改变时的回调"""
        self.apply_theme()

        # 通知托盘
        if hasattr(self, 'tray_icon'):
            theme_data = self.theme_manager.get_theme_data()
            self.tray_icon.showMessage(
                "主题已更换",
                f"已切换到 {theme_data['name']} 主题",
                QSystemTrayIcon.MessageIcon.Information,
                2000
            )

        # 强制重绘窗口
        self.update()

        # 如果分析对话框打开，也应用主题
        if hasattr(self, 'analysis_dialog') and self.analysis_dialog and self.analysis_dialog.isVisible():
            self.analysis_dialog.apply_theme(theme_data)

    def setup_system_tray(self):
        """设置系统托盘"""
        if QSystemTrayIcon.isSystemTrayAvailable():
            self.tray_icon = QSystemTrayIcon(self)

            # 设置托盘图标
            icon = QIcon(get_resource_path("assets/tray_icon.png"))
            # 如果没有图标文件，创建一个简单的图标
            pixmap = QPixmap(32, 32)
            pixmap.fill(QColor(59, 130, 246))
            icon.addPixmap(pixmap)
            self.tray_icon.setIcon(icon)

            # 创建托盘菜单
            tray_menu = QMenu()

            show_action = tray_menu.addAction("显示主窗口")
            show_action.triggered.connect(self.show_main_window)

            analysis_action = tray_menu.addAction("数据分析")
            analysis_action.triggered.connect(self.show_analysis_dialog)

            theme_action = tray_menu.addAction("主题设置")
            theme_action.triggered.connect(self.show_theme_dialog)

            tray_menu.addSeparator()

            background_action = tray_menu.addAction("后台运行")
            background_action.setCheckable(True)
            background_action.setChecked(True)
            background_action.triggered.connect(self.toggle_background_running)

            tray_menu.addSeparator()

            quit_action = tray_menu.addAction("退出程序")
            quit_action.triggered.connect(self.quit_application)

            self.tray_icon.setContextMenu(tray_menu)
            self.tray_icon.activated.connect(self.tray_icon_activated)

            # 显示托盘图标
            self.tray_icon.show()
            self.tray_icon.showMessage(
                "牛马监控",
                "程序已启动，正在后台监控工作状态",
                QSystemTrayIcon.MessageIcon.Information,
                3000
            )

    def tray_icon_activated(self, reason):
        """托盘图标激活事件"""
        if reason == QSystemTrayIcon.ActivationReason.DoubleClick:
            self.show_main_window()

    def show_main_window(self):
        """显示主窗口"""
        self.show()
        self.raise_()
        self.activateWindow()

    def toggle_background_running(self, checked):
        """切换后台运行状态"""
        self.is_background_running = checked
        if checked:
            self.monitor.start()
            # self.network_monitor.start()
            self.tray_icon.showMessage(
                "后台运行已开启",
                "程序将继续在后台监控",
                QSystemTrayIcon.MessageIcon.Information,
                2000
            )
        else:
            self.monitor.stop()
            # self.network_monitor.stop()
            self.tray_icon.showMessage(
                "后台运行已关闭",
                "监控已暂停",
                QSystemTrayIcon.MessageIcon.Warning,
                2000
            )

    def quit_application(self):
        """退出应用程序"""
        reply = QMessageBox.question(
            self,
            "确认退出",
            "确定要退出牛马监控程序吗？",
            QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
            QMessageBox.StandardButton.No
        )

        if reply == QMessageBox.StandardButton.Yes:
            self.monitor.stop()
            # self.network_monitor.stop()
            if self.analysis_dialog:
                self.analysis_dialog.close()
            QApplication.quit()

    def paintEvent(self, event):
        """绘制背景图片"""
        painter = QPainter(self)
        painter.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform)

        # 获取窗口尺寸
        window_rect = self.rect()

        if not self.background_pixmap.isNull():
            # 缩放背景图片以填充整个窗口
            scaled_pixmap = self.background_pixmap.scaled(
                window_rect.size(),
                Qt.AspectRatioMode.KeepAspectRatioByExpanding,
                Qt.TransformationMode.SmoothTransformation
            )

            # 计算居中位置
            x = (window_rect.width() - scaled_pixmap.width()) // 2
            y = (window_rect.height() - scaled_pixmap.height()) // 2

            # 绘制背景
            painter.drawPixmap(x, y, scaled_pixmap)

        # 添加半透明遮罩以提高可读性
        theme_data = self.theme_manager.get_theme_data()
        if "dark" in self.theme_manager.get_current_theme():
            overlay = QColor(0, 0, 0, 50)  # 深色主题使用黑色遮罩
        else:
            overlay = QColor(255, 255, 255, 30)  # 浅色主题使用白色遮罩
        painter.fillRect(window_rect, overlay)

        super().paintEvent(event)

    def create_header(self):
        self.header_frame = QFrame()
        self.header_frame.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True)
        self.header_frame.setFixedHeight(100)

        header_layout = QHBoxLayout(self.header_frame)
        header_layout.setContentsMargins(0, 0, 20, 0)

        # 左侧标题
        title_widget = QWidget()
        title_layout = QVBoxLayout(title_widget)
        title_layout.setSpacing(6)
        title_layout.setContentsMargins(0, 0, 0, 0)

        title_label = QLabel("牛马监控大屏")
        title_label.setFont(QFont("SF Pro Display", 22, QFont.Weight.Bold))
        title_label.setMinimumHeight(50)

        self.time_label = QLabel()
        self.time_label.setFont(QFont("SF Pro Display", 12))
        self.time_label.setMinimumHeight(50)

        title_layout.addWidget(title_label)
        title_layout.addWidget(self.time_label)

        # 右侧控制按钮
        controls_widget = QWidget()
        controls_layout = QHBoxLayout(controls_widget)
        controls_layout.setSpacing(10)
        controls_layout.setContentsMargins(0, 0, 0, 0)

        back_text = "⏸️ 暂停监控" if self.is_background_running else "▶️ 开始监控"
        # 后台运行按钮
        self.background_btn = QPushButton(back_text)
        self.background_btn.clicked.connect(self.toggle_monitoring)

        # 数据分析按钮
        analysis_btn = QPushButton("📊 数据分析")
        analysis_btn.clicked.connect(self.show_analysis_dialog)

        # 主题设置按钮
        theme_btn = QPushButton("🎨 主题设置")
        theme_btn.clicked.connect(self.show_theme_dialog)

        # 最小化到托盘按钮
        minimize_btn = QPushButton("📌 后台运行")
        minimize_btn.clicked.connect(self.hide)

        # 重置数据按钮
        reset_btn = QPushButton("🔄 重置数据")
        reset_btn.clicked.connect(self.reset_data)

        # 关闭按钮
        # close_btn = QPushButton("❌ 关闭")
        # close_btn.clicked.connect(self.close)

        controls_layout.addWidget(self.background_btn)
        controls_layout.addWidget(analysis_btn)
        controls_layout.addWidget(theme_btn)
        controls_layout.addWidget(minimize_btn)
        controls_layout.addWidget(reset_btn)
        # controls_layout.addWidget(close_btn)

        header_layout.addWidget(title_widget)
        header_layout.addStretch()
        header_layout.addWidget(controls_widget)

    def show_theme_dialog(self):
        """显示主题设置对话框"""
        theme_dialog = ThemeDialog(self.theme_manager, self)
        theme_dialog.theme_changed.connect(self.on_theme_changed)
        theme_dialog.exec()

    def on_theme_changed(self, theme_key):
        """主题改变时的回调"""
        self.apply_theme()

        # 通知托盘
        if hasattr(self, 'tray_icon'):
            theme_data = self.theme_manager.get_theme_data()
            self.tray_icon.showMessage(
                "主题已更换",
                f"已切换到 {theme_data['name']} 主题",
                QSystemTrayIcon.MessageIcon.Information,
                2000
            )

        # 强制重绘窗口
        self.update()

        # 如果分析对话框打开，也应用主题
        if hasattr(self, 'analysis_dialog') and self.analysis_dialog and self.analysis_dialog.isVisible():
            self.analysis_dialog.apply_theme(theme_data)

    def toggle_monitoring(self):
        """切换监控状态"""
        self.is_background_running = not self.is_background_running

        if self.is_background_running:
            self.monitor.start()
            # self.network_monitor.start()
            self.background_btn.setText("⏸️ 暂停监控")
            if hasattr(self, 'tray_icon'):
                self.tray_icon.showMessage(
                    "监控已开启",
                    "程序正在监控工作状态",
                    QSystemTrayIcon.MessageIcon.Information,
                    2000
                )
        else:
            self.monitor.stop()
            # self.network_monitor.stop()
            self.background_btn.setText("▶️ 开始监控")
            if hasattr(self, 'tray_icon'):
                self.tray_icon.showMessage(
                    "监控已暂停",
                    "点击开始监控按钮恢复",
                    QSystemTrayIcon.MessageIcon.Warning,
                    2000
                )

    def show_analysis_dialog(self):
        """显示数据分析对话框"""
        if self.analysis_dialog is None:
            self.analysis_dialog = AnalysisDialog(
                self.monitor,
                self.network_monitor,
                self
            )

        self.analysis_dialog.show()
        self.analysis_dialog.raise_()
        self.analysis_dialog.activateWindow()

    def resizeEvent(self, event):
        """窗口大小改变时重新绘制背景"""
        super().resizeEvent(event)
        self.update()  # 触发重绘

    def update_display(self):
        try:
            # 更新当前时间
            current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            self.time_label.setText(f"🕒 {current_time}")

            # 获取监控数据
            data = self.monitor.get_data()

            # 检查数据是否有显著变化
            data_summary = {
                'keystrokes': data['keystrokes'],
                'mouse_distance': int(data['mouse_distance']),
                'total_work_time': int(data['total_work_time']),
                'app_count': len(data['applications'])
            }

            if self._last_update_data == data_summary:
                return  # 数据没有变化，跳过更新

            self._last_update_data = data_summary

            # 更新键盘卡片
            work_time_minutes = data['total_work_time'] / 60
            avg_keys_per_min = int(data['keystrokes'] / work_time_minutes) if work_time_minutes > 0 else 0

            if avg_keys_per_min > self.peak_keys_per_min:
                self.peak_keys_per_min = avg_keys_per_min

            self.keyboard_card.update_value(
                f"{data['keystrokes']:,}",
                "次按键",
                min(data['keystrokes'] / 5000, 1.0)
            )

            self.keyboard_card.add_stat(0, 0, avg_keys_per_min, "平均每分钟")
            self.keyboard_card.add_stat(0, 1, self.peak_keys_per_min, "峰值每分钟")

            # 更新鼠标卡片
            mouse_distance_cm = data['mouse_distance'] * 0.0264583
            mouse_speed = mouse_distance_cm / work_time_minutes if work_time_minutes > 0 else 0

            self.mouse_card.update_value(
                f"{mouse_distance_cm:.1f}",
                "厘米",
                min(mouse_distance_cm / 1000, 1.0)
            )

            self.mouse_card.add_stat(0, 0, f"{mouse_speed:.1f}", "平均速度 cm/min")
            self.mouse_card.add_stat(0, 1, "%.2f" % data['mouse_distance'], "总像素")

            # 更新时间卡片
            work_time_str = self.format_time(data['total_work_time'])
            productivity = self.calculate_productivity(data)

            self.time_card.update_value(work_time_str, "今日工作时间", 0.5)

            self.time_card.add_stat(0, 0, len(data['applications']), "活跃应用")
            self.time_card.add_stat(0, 1, f"{productivity}%", "生产力指数")

            # 更新应用表格
            apps_list = list(data['applications'].values())
            self.app_table.update_apps(apps_list)

            # 更新托盘提示
            if hasattr(self, 'tray_icon') and self.is_background_running:
                tooltip = f"牛马监控 - 按键: {data['keystrokes']:,}, 工作时间: {work_time_str}"
                self.tray_icon.setToolTip(tooltip)

        except Exception as e:
            print(f"更新显示时出错: {e}")

    def format_time(self, seconds):
        hours = int(seconds // 3600)
        minutes = int((seconds % 3600) // 60)
        secs = int(seconds % 60)
        return f"{hours:02d}:{minutes:02d}:{secs:02d}"

    def calculate_productivity(self, data):
        work_time_hours = data['total_work_time'] / 3600
        keyboard_activity = min(data['keystrokes'] / 1000, 1)
        mouse_activity = min(data['mouse_distance'] * 0.0264583 / 1000, 1)
        return int((keyboard_activity + mouse_activity) * 50)

    def reset_data(self):
        reply = self.show_confirm_dialog("确定要重置所有数据吗？")
        if reply:
            self.monitor.reset_data()
            self.peak_keys_per_min = 0
            self._last_update_data = None
            if hasattr(self, 'tray_icon'):
                self.tray_icon.showMessage(
                    "数据已重置",
                    "所有监控数据已清空",
                    QSystemTrayIcon.MessageIcon.Information,
                    2000
                )

    def show_confirm_dialog(self, message):
        msg_box = QMessageBox(self)
        msg_box.setWindowTitle("确认")
        msg_box.setText(message)
        msg_box.setStandardButtons(QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No)
        msg_box.setDefaultButton(QMessageBox.StandardButton.No)
        return msg_box.exec() == QMessageBox.StandardButton.Yes

    def toggle_fullscreen(self):
        if self.isFullScreen():
            self.showNormal()
        else:
            self.showFullScreen()

    def keyPressEvent(self, event):
        if event.key() == Qt.Key.Key_F11:
            self.toggle_fullscreen()
        elif event.key() == Qt.Key.Key_F5:
            self.update_display()
        super().keyPressEvent(event)

    def closeEvent(self, event):
        # 关闭时最小化到托盘而不是退出
        if hasattr(self, 'tray_icon') and self.tray_icon.isVisible():
            self.hide()
            self.tray_icon.showMessage(
                "程序已最小化",
                "【牛马监控】将继续在后台运行",
                QSystemTrayIcon.MessageIcon.Information,
                2000
            )
            event.ignore()
        else:
            self.monitor.stop()
            # self.network_monitor.stop()
            if self.analysis_dialog:
                self.analysis_dialog.close()
            event.accept()


def main():
    app = QApplication(sys.argv)
    app.setQuitOnLastWindowClosed(False)  # 防止关闭最后一个窗口时退出

    # 设置应用样式
    app.setStyle('Fusion')

    # 设置字体
    font = QFont("SF Pro Display", 10)
    app.setFont(font)

    # 设置应用属性，减少闪烁
    app.setAttribute(Qt.ApplicationAttribute.AA_DontCreateNativeWidgetSiblings, True)

    window = MainWindow()
    window.show()

    sys.exit(app.exec())


if __name__ == "__main__":
    main()
